package org.zzh.service.cargo.contract;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zzh.dao.common.PageBean;
import org.zzh.dao.mapper.CoContractMapper;
import org.zzh.dao.mapper.CoContractProductMapper;
import org.zzh.domain.cargo.contract.CoContract;
import org.zzh.domain.system.user.PeUser;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class CoContractServiceImpl implements CoContractService {

    @Autowired
    CoContractMapper coContractMapper;

    @Autowired
    CoContractProductMapper coContractProductMapper;

    @Override
    public PageBean<CoContract> list(Integer page, Integer pageSize, String name, String companyId) {
        PageHelper.startPage(page, pageSize);
        List<CoContract> list = coContractMapper.list(name, companyId);
        PageInfo<CoContract> coContractPageInfo = new PageInfo<>(list);
        PageBean<CoContract> pageBean = new PageBean<>();
        pageBean.setData(coContractPageInfo.getList());
        pageBean.setTotalCount((int) coContractPageInfo.getTotal());
        pageBean.setTotalPage(coContractPageInfo.getPages());
        pageBean.setPage(page);
        pageBean.setPageSize(pageSize);
        return pageBean;
    }

    @Override
    public CoContract findById(String id) {
        return coContractMapper.findById(id);
    }

    @Transactional
    @Override
    public void edit(CoContract contract, PeUser user) {
        if (contract.getId() != null && !contract.getId().isEmpty()) {
            contract.setUpdateTime(new Date(System.currentTimeMillis()));
            contract.setUpdateBy(user.getUserId());
            coContractMapper.update(contract);
            return;
        }
        contract.setId(UUID.randomUUID().toString());
        contract.setCreateTime(new Date(System.currentTimeMillis()));
        contract.setCreateBy(user.getUserId());
        contract.setCompanyId(user.getCompanyId());
        contract.setCompanyName(user.getCompanyName());
        contract.setUpdateBy(user.getUserId());
        contract.setUpdateTime(new Date(System.currentTimeMillis()));
        coContractMapper.add(contract);
    }

    @Transactional
    @Override
    public void deleteList(String[] ids) {
        coContractMapper.deleteIds(ids);
        coContractProductMapper.deleteByContractIds(ids);
    }

    @Override
    @Transactional
    public void submit(String id) {
        CoContract contract = coContractMapper.findById(id);
        contract.setState(1L);
        coContractMapper.update(contract);
    }

}
